package com.guoguo.dao;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.guoguo.entity.ShortUrl;
import com.guoguo.utils.AbstractBaseMongoTemplete;

/**
 * @Description: mongo操作DAO参考
 */
@Repository
public class ShortUrlMongoDao extends AbstractBaseMongoTemplete {

	@Autowired
	private MongoTemplate mongoTemplate;

	/**
	 * 获取单个URL
	 *
	 * @param vo
	 * @return
	 * @throws Exception
	 */
	public ShortUrl getOne(String id, String oldUrl) throws Exception {
		ShortUrl shortUrl = mongoTemplate.findById(id, ShortUrl.class);
		return shortUrl;
	}

	/**
	 * 修改操作
	 *
	 * @param entity
	 * @throws Exception
	 */
	public void update(ShortUrl entity) throws Exception {
		Query query = new Query();
		query.addCriteria(new Criteria("_id").is(new ObjectId(entity.getId())));
		Update update = new Update();
		update.set("_id", new ObjectId(entity.getId()));
		update.set("oldUrl", entity.getOldUrl());
		update.set("newUrl", entity.getNewUrl());
		this.mongoTemplate.upsert(query, update, ShortUrl.class);
	}

	/**
	 * save函数根据参数条件,调用了insert或update函数:有则改之,无则加之
	 *
	 * @param entity
	 * @throws Exception
	 */
	public void save(ShortUrl entity) throws Exception {

		this.mongoTemplate.save(entity);
		/*
		 * Query query = new Query(); query.addCriteria(new
		 * Criteria("relationKeyId").is(entity.getRelationKeyId())); Update
		 * update = new Update(); update.set("createAt", new Date());
		 */
	}

	/**
	 * insert的对象如果存在则不会修改之前的值，也不会重新增加
	 *
	 * @param entity
	 * @throws Exception
	 */
	public void insert(ShortUrl entity) throws Exception {
		// save函数根据参数条件,调用了insert或update函数:有则改之,无则加之
		this.mongoTemplate.insert(entity);
	}

	/**
	 * 删除
	 *
	 * @param class
	 * @throws Exception
	 */
	public void delete(ShortUrl entity) throws Exception {
		Query query = new Query(Criteria.where("relationKeyId").is(entity.getId()));
		this.mongoTemplate.remove(query, ShortUrl.class);
	}

	public ShortUrl getById(String newUrl) throws Exception {
		Query query = new Query(Criteria.where("newUrl").is(newUrl));
		return this.mongoTemplate.findOne(query, ShortUrl.class);
	}

}
